package com.allwees.bs.c.module.product.controller;

import com.allwees.bs.c.module.base.controller.BaseController;
import com.allwees.bs.c.module.product.VoConvertor;
import com.allwees.bs.c.module.product.dto.ProductDetailsDTO;
import com.allwees.bs.c.module.product.dto.ProductReviewDTO;
import com.allwees.bs.c.module.product.service.ProductService;
import com.allwees.bs.core.model.ops.annotation.InsertAds;
import com.allwees.bs.core.model.product.annotation.FetchInventory;
import com.allwees.bs.core.model.product.entity.ProductModel;
import com.allwees.bs.core.modelbase.constant.ErrorMessage;
import com.allwees.bs.core.modelbase.page.PageParams;
import com.allwees.bs.core.modelbase.page.PaginateDTO;
import com.allwees.bs.core.modelbase.vo.R;
import com.allwees.support.api.compatible.ApiVersion;
import com.allwees.support.marketing.aop.ResetPrice;
import com.allwees.support.marketing.service.HotWordService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;

/**
 * 商品相关
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/api/v1/product")
public class ProductController extends BaseController implements VoConvertor {

    @Autowired
    private ProductService productService;

    @Autowired
    private HotWordService hotWordService;

    @GetMapping("/hws")
    public R hotWords() {
        return R.ok(hotWordService.first15());
    }

    /**
     * 商品列表 - 关键词模糊搜索
     *
     * @param keyword
     * @param pageParams
     * @return
     */
    @ResetPrice
    @GetMapping("/search")
    public R search(@RequestParam(value = "q") String keyword, PageParams pageParams) {
        PaginateDTO<ProductDetailsDTO> paginateDTO = productService.search(keyword, pageParams);
        setUserRelated(paginateDTO);
        return R.ok(convert(paginateDTO));
    }

    /**
     * 商品列表 - 指定类目
     *
     * @param categoryNo
     * @param pageParams
     * @return
     */
    @ResetPrice
    @GetMapping("/{categoryNo}")
    public R productsByCategory(@PathVariable("categoryNo") String categoryNo, PageParams pageParams) {
        return findList(categoryNo, pageParams);
    }

    @ApiVersion("2.0.0")
    @InsertAds
    @ResetPrice
    @GetMapping("/{categoryNo}")
    public R productByCategoryV2(@PathVariable("categoryNo") String categoryNo, PageParams pageParams) {
        return findList(categoryNo, pageParams);
    }

    private R findList(String categoryNo, PageParams pageParams) {
        PaginateDTO<ProductDetailsDTO> paginateDTO;
        //热销商品
        if (!StringUtils.isNumeric(categoryNo)) {
            paginateDTO = productService.findMarketingProducts(ProductModel.MARKETING_TYPE_8, pageParams);
        } else {
            paginateDTO = this.productService.getCategoryProducts(categoryNo, pageParams);
        }
        setUserRelated(paginateDTO);
        return R.ok(convert(paginateDTO));
    }

    /**
     * 热销商品列表
     *
     * @param keyCode
     * @return
     */
    @Deprecated
    @ResetPrice
    @GetMapping("/hot_sell/{keyCode}")
    public R getPageHotSellProducts(@PathVariable("keyCode") String keyCode, PageParams pageParams) {
        //return getCategoryProducts(keyCode, pageParams);
        log.info("===> call from unknown place...");
        return R.ok();
    }

    /**
     * 获取单个商品详情，只包括商品的基础信息，不包括可能出现无限多情况的数据，如评论列表，拼团列表等
     *
     * @param productUuid
     * @return
     */
    @FetchInventory
    @ResetPrice
    @GetMapping("/info/{productUuid}")
    public R getProduct(@NotBlank @PathVariable("productUuid") String productUuid) {
        ProductDetailsDTO product = setUserRelated(this.productService.getProductDetails(productUuid));
        return R.ok(product);
    }

    /**
     * 商品关联数据
     *
     * @param productUuid
     * @param count
     * @return
     */
    @ResetPrice
    @GetMapping("/related/{productUuid}")
    public R getRelatedProducts(@NotBlank @PathVariable("productUuid") String productUuid,
                                @RequestParam(name = "count", defaultValue = "10") Integer count) {
        count = Math.min(count, 20);
        List<ProductDetailsDTO> products = productService.getRelatedProducts(productUuid, count);
        products = productService.collectedOrBought(products, getUserUuid());
        return R.ok(products);
    }

    /**
     * 单个商品评价列表
     *
     * @param productUuid
     * @param current
     * @return
     */
    @GetMapping("/review/{productUuid}")
    public R getProductReviewList(
            @NotNull(message = "productUuid " + ErrorMessage.PARAM_NOT_NULL) @PathVariable("productUuid") String productUuid,
            @RequestParam(defaultValue = "1") Integer current) {
        current = Math.max(current, 1);
        ProductReviewDTO productReview = productService.getProductReviews(productUuid, current);
        return R.ok(productReview);
    }


    private void setUserRelated(PaginateDTO<ProductDetailsDTO> page) {
        if (CollectionUtils.isEmpty(page.getResults())) {
            return;
        }
        page.setResults(productService.collectedOrBought(page.getResults(), getUserUuid()));
    }

    private ProductDetailsDTO setUserRelated(ProductDetailsDTO dto) {
        if (dto == null) {
            return dto;
        }
        List<ProductDetailsDTO> dtos = new ArrayList<>(1);
        dtos.add(dto);
        dtos = productService.collectedOrBought(dtos, getUserUuid());
        return CollectionUtils.isEmpty(dtos) ? null : dtos.get(0);
    }
}
